package com.njtoyo.taxi.admin.library.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.logic.open.OnCallBacklogLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.OnCallBacklog;
import com.njtoyo.taxi.admin.mapper.master.mapper.OnCallBacklogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class OnCallBacklogRunner implements ApplicationRunner {

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Autowired
    private OnCallBacklogMapper onCallBacklogMapper;

    @Autowired
    private OnCallBacklogLogic onCallBacklogLogic;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        LambdaQueryWrapper<OnCallBacklog> wrapper = Wrappers.<OnCallBacklog>lambdaQuery()
                .isNull(OnCallBacklog::getSimpleCallId)
                .gt(OnCallBacklog::getExpectTimestamp, DateUtil.offsetMinute(new Date(), -10).getTime());
        List<OnCallBacklog> backlogs = onCallBacklogMapper.selectList(wrapper);

        log.info("项目重启时获取需发送的电召[on-call]数据 {}", backlogs);
        if (backlogs.size() > 0) {
            backlogs.forEach(backlog -> {
                if (backlog.getExpectTimestamp() < DateUtil.offsetMinute(new Date(), 30).getTime()) {
                    onCallBacklogLogic.sendOnCallBacklog(backlog.getId());
                } else {
                    taskScheduler.schedule(() -> onCallBacklogLogic.sendOnCallBacklog(backlog.getId()), new Date(backlog.getExpectTimestamp()));
                }
            });
        }
    }
}
